<?php

namespace App\Models;

use App\Models\Tools\AliOss;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Shop
{

    /**
     * 查询店铺信息
     * @param $shop_id
     * @return mixed
     */
    public static function shopMessage($shop_id)
    {
        $shop_message = DB::table('shop')
            ->leftJoin('lottery_users as lu', 'shop.we_id', '=', 'lu.we_id')
            ->leftJoin('dict_area as da', 'shop.district', '=', 'da.id')
            ->leftJoin('users', 'shop.verified_by', '=', 'users.id')
            ->where('shop.shop_id', '=', $shop_id)
            ->select('shop.shop_id', 'shop.we_id', 'shop.head_img', 'shop.key_word', 'shop.shop_type', 'shop.shop_name', 'shop.contact_man', 'shop.contact_phone', 'shop.province', 'shop.city', 'shop.district', 'shop.address', 'shop.link_url', 'shop.created_at', 'shop.verified',
                'lu.openid', 'lu.nickname', 'lu.phone', 'shop.verified_by', 'shop.verified_at', 'shop.verify_remark', 'users.name as verified_user', 'da.short_name')
            ->first();
        $shop_message->head_img = AliOss::getUrl($shop_message->head_img);
        $shop_message->verified_name = Data::$laifeiShopVerified[$shop_message->verified];
        return json_decode(json_encode($shop_message), true);
    }

    /**
     * 检查账号是否有审核通过的店铺
     * @param int $we_id
     * @return bool
     */
    public static function verified($we_id)
    {
        $verified = DB::table('shop')
            ->where('we_id', '=', $we_id)
            ->where('verified', '=', Data::DATA_DB_LAIFEI_SHOP_VERIFIED_SUCCESS)
            ->count();
        return $verified && true;
    }

    /**
     * 检查所有退款单是否已经处理完成
     * @param int $apply_id
     */
    public static function applyFinish($apply_id)
    {
        try {
            DB::beginTransaction();
            $refunds = DB::table('laifei_refund')->where('apply_id', '=', $apply_id)->lockForUpdate()->get();

            // 查询
            $apply = DB::table('explore_refund_apply')->where('apply_id', '=', $apply_id)->lockForUpdate()->first();
            $apply = json_decode(json_encode($apply), true);

            // 如果退款申请已经结束，后续不再操作
            if($apply['finish'] === 1){
                DB::rollBack();
                return;
            }

            // 余额id
            $remaining = DB::table('explore_remaining')
                ->where('we_id', '=', $apply['we_id'])
                ->where('channel_id', '=', $apply['channel_id'])
                ->lockForUpdate()
                ->first();
            $remaining = json_decode(json_encode($remaining), true);

            // 正在退款的加到成功，退款失败的加到退款失败
            $refunded_number = $refunds->where('status', '=', 2)->pluck('num')->sum(); // 退款成功数量
//        $return_number = $refunds->where('status', '=', 3)->pluck('num')->sum(); // 退款失败数量
            $refunding_number = $refunds->whereIn('status', [0, 1])->pluck('num')->sum(); // 待退款、正在退款的数量
            $return_number = $apply['number'] - $refunded_number - $refunding_number; // 退回数量 = 申请总数 - 已退回 - 正在退回

            // 如果正在退款的数量不为0，先不操作后续
            if ($refunding_number > 0){
                DB::rollBack();
                return;
            }
            // 每修改一次更新一次
            DB::table('explore_refund_apply')->where('apply_id', '=', $apply_id)->update([
                'finish' => $refunding_number === 0 ? 1 : 0, // 如果待退款和正在退款的数量不存在，那么这次退款结束
                'refunded_number' => $refunded_number,
                'refunding_number' => $refunding_number,
                'return_number' => $return_number,
            ]);

            // 如果完成，退回余额
            DB::table('explore_remaining')
                ->where('r_id', '=', $remaining['r_id'])
                ->increment('remaining_times', $return_number);
            if($return_number > 0){
                // 记录日志
                DB::table('explore_remaining_log')->insert([
                    'r_id' => $remaining['r_id'],
                    'action' => Data::DATA_DB_EXPLORE_REMAINING_LOG_TYPE_REFUND_FAILED,
                    'action_num' => $return_number,
                    'rest_num' => $remaining['remaining_times'] + $return_number,
                    'in_use_num' => $remaining['in_use_times'],
                ]);
            }
            DB::commit();
        } catch (\Exception $e) {
            Log::emergency(Shop::class, ['apply_id' => $apply_id, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            DB::rollBack();
        }


    }

}
